package com.cynteka.cyfoman.core.collection;

import com.cynteka.cyfoman.core.ComplexPropertyResolver;
import com.cynteka.cyfoman.core.IPropertyResolver;
import com.cynteka.cyfoman.core.config.ColumnMD;

import java.util.*;

/**
 * User: Sergey
 * Date: 06.08.11
 * Time: 14:27
 */
public class SubCollection<T> extends BaseCollection<T> {

    private List<String> collectionIds;
    private String keyColumn;
    private List<ColumnMD> columns;

    public List<String> getCollectionIds() {
        return collectionIds;
    }

    public void setCollectionIds(List<String> collectionIds) {
        this.collectionIds = collectionIds;
    }

    public String getKeyColumn() {
        return keyColumn;
    }

    public void setKeyColumn(String keyColumn) {
        this.keyColumn = keyColumn;
    }

    public List<ColumnMD> getColumns() {
        return columns;
    }

    public void setColumns(List<ColumnMD> columns) {
        this.columns = columns;
    }

    public IPropertyResolver getPropertyResolver() {
        return propertyResolver;
    }

    public void setPropertyResolver(IPropertyResolver propertyResolver) {
        this.propertyResolver = propertyResolver;
    }

    private IPropertyResolver propertyResolver = new ComplexPropertyResolver();

    public SubCollection(String id) {
        super(id);
    }

    @Override
    public Collection<T> getItems(Map<String, Object> params) {
        int i = 0;
        Set keys = new HashSet();
        Collection firstCollection = null;
        for(String collectionId : collectionIds) {
            ICollection collection = getOwner().getCollection(collectionId);
            Collection items = collection.getItems(params);
            if(i == 0) {
                firstCollection = items;
            }
            if(items != null) {
                for(Object item : items) {
                    Object keyValue = propertyResolver.getProperty(item, keyColumn);
                    if(i == 0) {
                        keys.add(keyValue);
                    } else {
                        keys.remove(keyValue);
                    }
                }
            }
            i++;
        }
        Collection res = new ArrayList();
        for(Object item : firstCollection) {
            Object keyValue = propertyResolver.getProperty(item, keyColumn);
            if(keys.contains(keyValue))
                res.add(item);
        }
        return res;
    }
}
